package com.jichangxiu.framework.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jichangxiu.common.context.JcxContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

@Slf4j
public class BaseMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String deptId = JcxContext.getDeptId();
        String userId = JcxContext.getUserId();
        log.debug("【BaseMetaObjectHandler】自动填充创建者、创建时间");
        String deptBy = (String) getFieldValByName("deptBy", metaObject);
        if (StrUtil.isEmpty(deptBy) && StrUtil.isNotEmpty(deptId))
            setFieldValByName("deptBy", deptId, metaObject);
        String createBy = (String) getFieldValByName("createBy", metaObject);
        if (StrUtil.isEmpty(createBy) && StrUtil.isNotEmpty(userId))
            setFieldValByName("createBy", userId, metaObject);
        Date createTime = (Date) getFieldValByName("createTime", metaObject);
        if (ObjectUtil.isEmpty(createTime))
            setFieldValByName("createTime", new Date(), metaObject);
        String updateBy = (String) getFieldValByName("updateBy", metaObject);
        if (StrUtil.isEmpty(updateBy) && StrUtil.isNotEmpty(userId))
            setFieldValByName("updateBy", userId, metaObject);
        Date updateTime = (Date) getFieldValByName("updateTime", metaObject);
        if (ObjectUtil.isEmpty(updateTime))
            setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = JcxContext.getUserId();
        log.debug("【BaseMetaObjectHandler】自动填充更新者、更新时间");
        String updateBy = (String) getFieldValByName("updateBy", metaObject);
        if (StrUtil.isEmpty(updateBy) && StrUtil.isNotEmpty(userId))
            setFieldValByName("updateBy", userId, metaObject);
        Date updateTime = (Date) getFieldValByName("updateTime", metaObject);
        if (ObjectUtil.isEmpty(updateTime))
            setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public boolean openInsertFill() {
        return true;
    }

    @Override
    public boolean openUpdateFill() {
        return true;
    }

}
